export class RSAEncryptor {
    private publicKeyBase64: string;
    private publicKey?: CryptoKey;

    constructor(publicKeyBase64: string) {
        this.publicKeyBase64 = publicKeyBase64;
    }

    private async importPublicKey(): Promise<CryptoKey> {
        if (!this.publicKey) {
            const publicKeyArray = Uint8Array.from(atob(this.publicKeyBase64), c => c.charCodeAt(0));
            this.publicKey = await window.crypto.subtle.importKey(
                "spki",
                publicKeyArray,
                {
                    name: "RSA",
                    hash: {name: "SHA-256"}
                },
                true,
                ["encrypt"]
            );
        }
        return this.publicKey!;
    }

    public async encryptData(data: string): Promise<string> {
        const publicKey = await this.importPublicKey();
        const encodedData = new TextEncoder().encode(data);
        const encrypted = await window.crypto.subtle.encrypt(
            {
                name: "RSA-OAEP"
            },
            publicKey,
            encodedData
        );
        return btoa(String.fromCharCode(...new Uint8Array(encrypted)));
    }
}